package com.lfg.leetcode.leetcode0;


public class No44IsMatch2 {

    public static void main(String[] args) {
        boolean ret = isMatch("aaaa", "***a");
        System.out.println(ret);
    }

    public static boolean isMatch(String s, String p) {
        if (null == s && null == p) {
            return true;
        }
        if (null == s || null == p) {
            return false;
        }
        if (s.equals(p)) {
            return true;
        }
        if ("".equals(p)) {
            return false;
        }
        StringBuilder sb = new StringBuilder();

        if (p.length() > 0) {
            sb.append(p.charAt(0));
        }
        for (int i = 1; i < p.length(); i++) {
            if (p.charAt(i) == p.charAt(i - 1) && p.charAt(i - 1) == '*') {
                continue;
            }
            sb.append(p.charAt(i));
        }
        p = sb.toString();
        int pl = p.length();
        int sl = s.length();
        boolean[][] dp = new boolean[pl + 1][sl + 1];
        int i = 0;
        int j = 0;
        dp[i][j] = true;
        if (p.charAt(0) == '*') {
            dp[1][0] = true;
        }
        for (i = 1; i <= pl; i++) {
            for (j = 1; j <= sl; j++) {
                if (p.charAt(i - 1) == '*') {
                    dp[i][j] = dp[i][j - 1] || dp[i - 1][j - 1] || dp[i - 1][j];
                } else {
                    dp[i][j] = dp[i - 1][j - 1] && (p.charAt(i - 1) == '?' || p.charAt(i - 1) == s.charAt(j - 1));
                }
            }
        }
        return dp[pl][sl];
    }
}

